﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

using TravelSite.DAL;
using TravelSite.DAL.Repositories;
using TravelSite.Entities;
using TravelSite.Code;
using System.Globalization;
using OfficeOpenXml;

namespace TravelSite.Admin.Bookings
{
    public partial class BankInfoPage : BaseBookingPage
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            PageName = "Bookings_BankInfo";
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                grid.PageSize = DefaultPageSize;
                LoadDataFromDb();
                LoadData();
                LoadPageSizes(ddlPageSizeFilter);
            }
        }

        public override void LoadData()
        {
            grid.DataSource = GridViewData;
            grid.DataBind();
        }

        protected void LoadDataFromDb()
        {
            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                DateTime? dateFrom = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtFromDateFilter.Text))
                        dateFrom = DateTime.ParseExact(txtFromDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date From not valid!'); }, 150);", true);
                    return;
                }

                DateTime? dateTo = null;
                try
                {
                    if (!string.IsNullOrEmpty(txtToDateFilter.Text))
                        dateTo = DateTime.ParseExact(txtToDateFilter.Text, "d", new CultureInfo("en-US"));
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Date To not valid!'); }, 150);", true);
                    return;
                }

                GridData = repo.BankInfoList(dateFrom, dateTo).ToList();
            }
        }

        protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grid.PageIndex = e.NewPageIndex;
            LoadData();
        }

        protected void grid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortExpression = e.SortExpression;
            LoadData();
        }

        protected void grid_RowCommand(object sender, CommandEventArgs e)
        {
            //int id = Convert.ToInt32(e.CommandArgument.ToString());

            /*using (var repo = RepositoryFactory.ResolveRepository<BankInfoRepository>())
            {
                switch (e.CommandName)
                {
                    case "delete":
                        repo.Delete(id);
                        break;
                }
            }
            LoadData();*/
        }

        protected override void grid_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
            base.grid_RowDataBound(sender, e);

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (IsEmptyGrid)
                {
                    e.Row.Attributes.Add("style", "display:none;");
                    return;
                }

                Contact item = (Contact)e.Row.DataItem;

                if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                {
                    Control btn = e.Row.FindControl("btnShowBankInfoDate");
                    TextBox tb = (TextBox)e.Row.FindControl("txtBankInfoDate");
                    if (item.BankInfoDate.HasValue)
                        tb.Text = item.BankInfoDate.Value.ToString("d", new CultureInfo("en-US"));
                    ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "DateEditInit", string.Format("SetGridDateEdit('{0}', '{1}')", tb.ClientID, btn.ClientID), true);
                    
                    tb = (TextBox)e.Row.FindControl("txtBankInfoAmount");
                    if (item.BankInfoAmount.HasValue)
                        tb.Text = item.BankInfoAmount.Value.ToString("N", new CultureInfo("en-US"));

                    DropDownList ddl = (DropDownList)e.Row.FindControl("ddlBankInfoPayment");
                    using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
                    {
                        ddl.DataSource = repo.PaymentsCombo(false, true);
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.BankInfoPaymentId.HasValue)
                            ddl.SelectedValue = item.BankInfoPaymentId.Value.ToString();
                    }

                    ddl = (DropDownList)e.Row.FindControl("ddlBankInfoVacationCompany");
                    using (var repo = RepositoryFactory.ResolveRepository<VacationCompanyRepository>())
                    {
                        List<VacationCompany> vacCompany = repo.FindAll().ToList();
                        ddl.DataSource = vacCompany;
                        ddl.DataBind();
                        ddl.SelectedValue = "-1";
                        if (item.VacationCompanyId.HasValue)
                            ddl.SelectedValue = item.VacationCompanyId.Value.ToString();
                        else
                        {
                            VacationCompany defCompany = vacCompany.FirstOrDefault(x => x.IsDefault);
                            if (defCompany != null)
                            {
                                ddl.SelectedValue = defCompany.VacationCompanyId.ToString();
                            }
                        }
                    }
                    
                }
                else
                {
                    Label lbl = (Label)e.Row.FindControl("lblBankInfoDate");
                    if (item.BankInfoDate.HasValue)
                        lbl.Text = item.BankInfoDate.Value.ToString("MM/dd/yyyy");

                    lbl = (Label)e.Row.FindControl("lblBankInfoAmount");
                    if (item.BankInfoAmount.HasValue)
                        lbl.Text = item.BankInfoAmount.Value.ToString("$#,##0.00");
                }
                
                /*BankInfo item = (BankInfo)e.Row.DataItem;

                ImageButton ibtn = (ImageButton)e.Row.FindControl("lbtnDelete");
                ibtn.Visible = item.CanDelete;*/
            }
        }

        protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            grid.EditIndex = -1;
            LoadData();
        }

        protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = grid.Rows[e.RowIndex];
            int contactId = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value);

            DateTime? bankInfoDate = null;
            TextBox tb = (TextBox)row.FindControl("txtBankInfoDate");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    bankInfoDate = DateTime.ParseExact(tb.Text, "d", new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Bank Info Date not valid!'); }, 150);", true);
                return;
            }

            decimal? bankInfoAmount = null;
            tb = (TextBox)row.FindControl("txtBankInfoAmount");
            try
            {
                if (!string.IsNullOrEmpty(tb.Text))
                    bankInfoAmount = decimal.Parse(tb.Text, new CultureInfo("en-US"));
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "Alert", "setTimeout(function() { alert('Bank Info Amount not valid!'); }, 150);", true);
                return;
            }

            Contact itm = new Contact();
            itm.ContactId = contactId;
            itm.BankInfoDate = bankInfoDate;
            itm.BankInfoAmount = bankInfoAmount;
            DropDownList ddl = (DropDownList)row.FindControl("ddlBankInfoPayment");
            itm.BankInfoPaymentId = ddl.SelectedValue == "-1" ? (int?)null : Convert.ToInt32(ddl.SelectedValue);
            ddl = (DropDownList)row.FindControl("ddlBankInfoVacationCompany");
            itm.VacationCompanyId = Convert.ToInt32(ddl.SelectedValue);

            using (var repo = RepositoryFactory.ResolveRepository<ContactRepository>())
            {
                repo.UpdateBankInfo(itm);
            }

            grid.EditIndex = -1;
            LoadDataFromDb();
            LoadData();
        }

        protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
        {
            grid.EditIndex = e.NewEditIndex;
            LoadData();
        }

        protected void btnExcelExport_Click(object sender, EventArgs e)
        {
            List<Contact> data = GridViewData;
            string pageName = "BankInfo";
            List<string> headers = new List<string>();
            for (int i = 1; i < grid.Columns.Count; ++i)
            {
                headers.Add(grid.Columns[i].HeaderText);
            }
            List<string> fields = new List<string>();
            fields.AddRange(new string[] { "FullName", "BankInfoDate", "BankInfoAmount", "PaymentName", "VacationCompanyName" });
            List<string> format = new List<string>();
            format.AddRange(new string[] { "", "MM/dd/yyyy", "#,##0.00", "", "" });

            ExcelPackage pck = Common.DataToExcel(data.Cast<object>().ToList(), headers, fields, format, pageName);

            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;  filename=" + pageName + ".xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.BinaryWrite(pck.GetAsByteArray());
            Response.End();

        }

        protected void ddlPageSizeFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            string size = ddlPageSizeFilter.SelectedItem.Text;
            grid.AllowPaging = (size != "All");
            if (grid.AllowPaging)
            {
                grid.PageSize = Convert.ToInt32(size);
            }
            grid.PageIndex = 0;
            LoadData();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadDataFromDb();
            LoadData();
        }
    }
}